# _*_ coding:utf-8 _*_
# @Time  : 2023.10.24
# @Author: zizlee

from utils.jwt_token import TokenPayload
from constant.user import UserType
from db_utils import BaseDatabaseConnection


class ModulePublic:
    def __init__(self, module_key: str, module_sec: str):
        self.module_key = module_key  # 模块中品种的scope
        self.module_sec = module_sec  # 模块的sec_key

    def access_variety(self, payload: TokenPayload, update_dict: dict = None, auto_tree: int = 0):
        utp = payload.user_type()
        if utp == UserType.REGISTER_USER:
            return [] # 全无
        # 全有
        a_sql = "SELECT id,`code`,`name`,group_id,multiplier FROM ruizhi_variety WHERE is_active=1 AND FIND_IN_SET(%s,scope) ORDER BY sort_num;"
        a_prm = [self.module_key]

        # 看权限
        b_sql = """
            SELECT * FROM ruizhi_user_section_variety As a
            INNER JOIN ruizhi_variety As b ON a.variety_en=b.code
            WHERE a.sec_key=%s AND a.active_expire>=CURDATE() AND a.user_id=%s;
        """

        b_prm = [self.module_sec, payload.user_id()]

        sql = a_sql
        prm = a_prm
        with BaseDatabaseConnection() as conn:
            if utp in UserType.VARIETY_AUTH_SETS:
                # 查询用户是不是全品种
                conn.cursor.execute("SELECT id FROM ruizhi_user_section_variety WHERE sec_key=%s AND variety_en='VAR_ALL' AND user_id=%s AND expire_date>=CURDATE() LIMIT 1;",
                                    [self.module_sec, payload.user_id()])
                all_access = conn.cursor.fetchone()
                if not all_access:
                    sql = b_sql
                    prm = b_prm
            conn.cursor.execute(sql, prm)
            variety_list = list(conn.cursor.fetchall())
        return variety_list
